import { registerIndicator } from 'klinecharts'
import { userStore } from '@/store/user.js'
import { useCoinStore } from '@/store/coin.js'
import { kanbanStore } from '@/store/user.js'
import { useSettingsStore } from '@/store/theme.js'


export function registerIndicatorMa() {
    const calcParams = userStore().mainIndicator.ma.list.filter((item: any) => item.checked).map((item: any) => item.value)
    const figures = userStore().mainIndicator.ma.list.filter((item: any) => item.checked).map((item: any) => {
        const obj = {
            key: item.key,
            title: item.title,
            lineType: item.lineType,
            type: 'line',
            styles: () => {
                return { color: item.color, size: item.lineSize }
            }
        }
        obj.key = `MA(${item.value})`
        return obj
    })
    registerIndicator({
        name: 'MA',
        shortName: 'MA',
        calcParams,
        figures,
        calc: (kLineDataList, { calcParams }) => {
            const closeSums: number[] = []
            const list = kLineDataList.map((kLineData, i) => {
                const ma = {} as Record<string, number>
                calcParams.forEach((param, j) => {
                    const data = kLineData[figures[j].lineType]
                    closeSums[j] = (closeSums[j] || 0) + data
                    if (i >= param - 1) {
                        ma[`MA(${calcParams[j]})`] = closeSums[j] / param
                        closeSums[j] -= kLineDataList[i - (param - 1)][figures[j].lineType]
                    }
                })
                return ma
            })
            useCoinStore().setMA(list[list.length - 1])
            return list
        },
    })
}


export function registerIndicatorEma() {
    const calcParams = userStore().mainIndicator.ema.list.filter((item: any) => item.checked).map((item: any) => item.value)
    const figures = userStore().mainIndicator.ema.list.filter((item: any) => item.checked).map((item: any) => {
        const obj = {
            key: item.key,
            title: item.title,
            type: 'line',
            styles: () => {
                return { color: item.color, size: item.lineSize }
            }
        }
        obj.key = `EMA(${item.value})`
        return obj
    })
    registerIndicator({
        name: 'EMA',
        shortName: 'EMA',
        calcParams,
        figures,
        calc: (kLineDataList, { calcParams }) => {
            let closeSum = 0;
            const emaValues: number[] = [];
            const list = kLineDataList.map((kLineData, i) => {
                const ema = {} as Record<string, number>
                const close = kLineData.close;
                closeSum += close;
                calcParams.forEach((p, index) => {
                    if (i >= p - 1) {
                        if (i > p - 1) {
                            emaValues[index] = (2 * close + (Number(p) - 1) * emaValues[index]) / (Number(p) + 1);
                        } else {
                            emaValues[index] = closeSum / Number(p);
                        }
                        ema[`EMA(${calcParams[index]})`] = emaValues[index];
                    }
                });

                return ema;
            });
            useCoinStore().setEMA(list[list.length - 1])
            return list
        },
    })
}





export function registerIndicatoVol() {
    const calcParams = userStore().mainIndicator.vol.list.filter((item: any) => item.checked).map((item: any) => item.value)
    const figures = userStore().mainIndicator.vol.list.filter((item: any) => item.checked).map((item: any) => {
        const obj = {
            key: item.key,
            title: item.title,
            type: 'line',
            styles: () => {
                return { color: item.color, size: item.lineSize }
            }
        }
        obj.key = `VOLMA(${item.value})`
        return obj
    })
    registerIndicator({
        name: 'VOL',
        shortName: 'VOL',
        minValue: 0,
        calcParams,
        figures: [
            ...figures,
            {
                key: 'vol', title: 'VOL: ', type: 'bar', styles: (data) => {
                    const data1 = data.current?.kLineData;
                    if (data1?.close && data1?.open && data1.close > data1.open) {
                        return { color: useSettingsStore().greenRise ? '#2dbd85' : '#f6475d', borderColor: useSettingsStore().greenRise ? '#2dbd85' : '#f6475d', style: userStore().mainIndicator.vol.barType.long };
                    }
                    return { color: useSettingsStore().greenRise ? '#f6475d' : '#2dbd85', borderColor: useSettingsStore().greenRise ? '#f6475d' : '#2dbd85', style: userStore().mainIndicator.vol.barType.short };
                }
            },
        ],
        calc: (kLineDataList, { calcParams, figures }) => {
            const closeSums: any = []
            const list = kLineDataList.map((kLineData, i) => {
                const ma: any = {}
                ma['vol'] = kLineData.volume
                const close = kLineData.volume
                calcParams.forEach((param, j) => {
                    closeSums[j] = (closeSums[j] || 0) + close
                    if (i >= param - 1) {
                        ma[figures[j].key] = closeSums[j] / param
                        const prevKLineData = kLineDataList[i - (param - 1)];
                        if (prevKLineData) {
                            if (prevKLineData?.volume !== undefined) {
                                closeSums[j] -= prevKLineData.volume;
                            }
                        }
                    }
                })
                return ma
            })
            useCoinStore().setVOL(list[list.length - 1])
            return list
        }
    })
}


export function registerIndicatoMacd() {
    const calcParams = userStore().mainIndicator.macd.periodList.map((item: any) => Number(item.value))
    const figures = userStore().mainIndicator.macd.list.filter((item: any) => item.checked).map((item: any) => {
        const obj: any = {
            key: item.title,
            title: item.title,
            type: 'line',
            baseValue: 0,
            styles: () => {
                return {}
            }
        }
        if (item.code === 'macd') {
            obj.type = 'bar'
            obj.styles = (data: any) => {
                const { prev, current } = data
                const prevMacd = prev?.indicatorData?.MACD ?? Number.MIN_SAFE_INTEGER
                const currentMacd = current?.indicatorData?.MACD ?? Number.MIN_SAFE_INTEGER
                let color = ''
                let style = ''
                //long
                if (currentMacd >= 0) {
                    if (prevMacd < currentMacd) {
                        color = userStore().mainIndicator.macd.type.LongGrow.color
                        style = userStore().mainIndicator.macd.type.LongGrow.type
                    } else {
                        color = userStore().mainIndicator.macd.type.LongFall.color
                        style = userStore().mainIndicator.macd.type.LongFall.type
                    }
                } else if (currentMacd < 0) {
                    if (prevMacd < currentMacd) {
                        color = userStore().mainIndicator.macd.type.ShortGrow.color
                        style = userStore().mainIndicator.macd.type.ShortGrow.type
                    } else {
                        color = userStore().mainIndicator.macd.type.ShortFall.color
                        style = userStore().mainIndicator.macd.type.ShortFall.type
                    }
                }
                return { style, color, borderColor: color }
            }

        } else {
            obj.styles = () => {
                return { color: item.color, size: item.lineSize }
            }

        }
        return obj
    })
    registerIndicator({
        name: 'MACD',
        shortName: 'MACD',
        calcParams,
        figures,
        calc: (kLineDataList, { calcParams }) => {
            let closeSum = 0
            let emaShort = 0
            let emaLong = 0
            let dif = 0
            let difSum = 0
            let dea = 0
            const maxPeriod = Math.max(calcParams[0], calcParams[1])
            const list = kLineDataList.map((kLineData, i) => {
                const macd = {} as Record<string, number>
                const close = kLineData.close
                closeSum += close
                if (i >= calcParams[0] - 1) {
                    emaShort = i > calcParams[0] - 1
                        ? (2 * close + (calcParams[0] - 1) * emaShort) / (calcParams[0] + 1)
                        : closeSum / calcParams[0]
                }
                if (i >= calcParams[1] - 1) {
                    emaLong = i > calcParams[1] - 1
                        ? (2 * close + (calcParams[1] - 1) * emaLong) / (calcParams[1] + 1)
                        : closeSum / calcParams[1]
                }
                if (i >= maxPeriod - 1) {
                    dif = emaShort - emaLong
                    macd[`DIF`] = dif
                    difSum += dif
                    if (i >= maxPeriod + calcParams[2] - 2) {
                        dea = i > maxPeriod + calcParams[2] - 2
                            ? (dif * 2 + dea * (calcParams[2] - 1)) / (calcParams[2] + 1)
                            : difSum / calcParams[2]
                        macd[`DEA`] = dea
                        macd[`MACD`] = (dif - dea) * 2
                    }
                }

                return macd
            })
            useCoinStore().setMACD(list[list.length - 1])
            return list
        }
    })
}


export function registerIndicatorMa1(type: string, index: number) {
    const calcParams = (kanbanStore()[type as keyof ReturnType<typeof kanbanStore>] as any[])[index].mainIndicator.ma.list.filter((item: any) => item.checked).map((item: any) => item.value)
    const figures = (kanbanStore()[type as keyof ReturnType<typeof kanbanStore>] as any[])[index].mainIndicator.ma.list.filter((item: any) => item.checked).map((item: any) => {
        const obj = {
            key: item.key,
            title: item.title,
            lineType: item.lineType,
            type: 'line',
            styles: () => {
                return { color: item.color, size: item.lineSize }
            }
        }
        obj.key = `MA(${item.value})`
        return obj
    })
    registerIndicator({
        name: 'MA',
        shortName: 'MA',
        calcParams,
        figures,
        calc: (kLineDataList, { calcParams }) => {
            const closeSums: number[] = []
            const list = kLineDataList.map((kLineData, i) => {
                const ma = {} as Record<string, number>
                calcParams.forEach((param, j) => {
                    const data = kLineData[figures[j].lineType]
                    closeSums[j] = (closeSums[j] || 0) + data
                    if (i >= param - 1) {
                        ma[`MA(${calcParams[j]})`] = closeSums[j] / param
                        closeSums[j] -= kLineDataList[i - (param - 1)][figures[j].lineType]
                    }
                })
                return ma
            })
            kanbanStore().setMainIndicatorInfo(type, index, 'infoMA', list[list.length - 1])
            return list
        },
    })
}